<?php

namespace common\models;

use crazyfd\qiniu\Qiniu;
use Exception;
use yii\base\Model;

class CosModel extends Model
{

    /**
     * @var
     */
    public $file;

    /**
     * @var string ak
     */
    public $ak;

    /**
     * @var string sk
     */
    public $sk;

    /**
     * @var string 存储空间
     */
    public $bucket;

    /**
     * @var string cdn url
     */
    public $domain;

    /**
     * @var string 区域
     */
    public $zone;


    public function rules()
    {
        return [
            [['file'], 'file', 'skipOnEmpty' => false],
        ];
    }


    public function init()
    {
        $this->ak     = \Yii::$app->params['cdn']['accessKey'];
        $this->sk     = \Yii::$app->params['cdn']['secretKey'];
        $this->bucket = \Yii::$app->params['cdn']['bucket'];
        $this->domain = \Yii::$app->params['cdn']['cdnUrl'];
        $this->zone   = \Yii::$app->params['cdn']['zone'];
    }

    /**
     * @return string
     * @throws Exception
     */
    public function upload()
    {
        if ($this->validate()) {

            $qiniu = new Qiniu($this->ak, $this->sk, $this->domain, $this->bucket, $this->zone);
            $key   = time();
            $key   .= $this->getFileName();

            $qiniu->uploadFile($this->file->tempName, $key);
            return $qiniu->getLink($key);

        } else {
            throw new Exception(current($this->getFirstErrors()));
        }
    }

    /**
     * @return string
     * @throws Exception
     */
    public function uploadByWx($file)
    {
        $qiniu = new Qiniu($this->ak, $this->sk, $this->domain, $this->bucket, $this->zone);
        $key   = time();

        $qiniu->uploadFile($file, $key);
        return $qiniu->getLink($key);

    }

    /**
     * @param int $count
     *
     * @return string
     */
    public function getFileName($count = 0)
    {
        if ($count == 0) {
            $fileName = $this->file->baseName . '.' . $this->file->extension;
        } else {
            $fileName = $this->file->baseName . "($count)" . '.' . $this->file->extension;
        }

        return $fileName;
    }


}